package com.ndp.fb.walle.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.ndp.ec.core.FeedService;
import com.ndp.ec.core.UserService;
import com.ndp.ec.core.api.ProductFeedService;
import com.ndp.fb.constant.CommonConstants;
import com.ndp.fb.enums.ErrorType;
import com.ndp.fb.enums.message.ChannelType;
import com.ndp.fb.enums.productfeed.FeedWeCreatingStatus;
import com.ndp.fb.exception.CheckedException;
import com.ndp.fb.fbagent.service.ProductCatalogFBService;
import com.ndp.fb.mq.api.producer.EventNotificationMessageProducerService;
import com.ndp.fb.rdb.model.FeedWe;
import com.ndp.fb.rdb.model.Pager;
import com.ndp.fb.rdb.model.User;
import com.ndp.fb.rdb.model.product.FeedWeWithMateriel;
import com.ndp.fb.rdb.model.product.ProductCatalogStatusCheck;
import com.ndp.fb.rdb.model.product.ProductCatalogStatusCheckResult;
import com.ndp.fb.util.ListUtil;
import com.ndp.fb.util.StringUtil;
import com.ndp.fb.walle.model.vo.PageResult;
import com.ndp.fb.walle.model.vo.adpublishcondition.param.SearchListParam;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by Evan on 2016/4/14.
 */
@RestController
@RequestMapping("/feed")
public class FeedController {
    private final org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());

    @Reference
    UserService userService;

    @Reference
    FeedService feedService;

    @Reference
    ProductFeedService productFeedService;

    @Reference
    private ProductCatalogFBService productCatalogFBService;

    @Autowired
    EventNotificationMessageProducerService eventNotificationMessageProducerService;


    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Long saveFeed(@RequestBody FeedWe param, HttpServletRequest req)throws Exception{
        User user = (User) req.getSession().getAttribute("user");
        //校验角色 非管理员不能save
        List<Long> roleIds = userService.getRoleByUser(user.getId());
        if (param != null && ListUtil.isNotEmpty(roleIds) && (roleIds.contains(CommonConstants.ROLE_ADMIN))) {
            param.setOrgId(user.getOrgId());
            param.setUserId(user.getTicket());
            param.setNickName(StringUtil.isEmpty(user.getNickname())?user.getUsername():user.getNickname());
            param.setCreateTime(System.currentTimeMillis());
            param.setCountry("US"); //国家默认写死

            if (param.getOperateStatus().equals(FeedWeCreatingStatus.UNBIND_CATALOG.getStatus())) {
                //绑定已有catalog
                feedService.save(param);
            }else {
                //创建新的catalog
                param.setOperateStatus(FeedWeCreatingStatus.FEEDWE_WAIT_SEND.getStatus());
                feedService.saveAndCreateOnFb(param);
            }
            return 1L;
        } else {
            throw new CheckedException(ErrorType.PARAM_EXCEPTION);
        }
    }
    @RequestMapping(value = "update", method = RequestMethod.POST)
    @ResponseBody
    public Long updateFeed(@RequestBody FeedWe param, HttpServletRequest req)throws Exception{
        //校验角色 非管理员不能update
        User user = (User) req.getSession().getAttribute("user");
        List<Long> roleIds = userService.getRoleByUser(user.getId());
        if (ListUtil.isNotEmpty(roleIds) && (roleIds.contains(CommonConstants.ROLE_ADMIN))) {
            return feedService.updateFeed(param);
        } else {
            throw new CheckedException(ErrorType.PARAM_EXCEPTION);
        }
    }

    @RequestMapping("test")
    public void overview(HttpServletRequest req)throws Exception{
        //catalogService.catalogChecks();
        productFeedService.updateFeedStatus();
//        ProductCatalogParam param = new ProductCatalogParam();
//        param.setAccessToken("CAAEJqYBYwW0BAH8hd4blFCEf5Wz2xMoImCG9ZAFil9ohifO7uKTyLt7fy4ybxM5Q4qQLaqsI0IQ5hBN8RUYGK2hWYTzfkQ0aKh9ywrK8AO5ueS2UKocq9ZAXGb5WK55QZANxbBUyqeHLJQMRFtk2S8rwX8iK6qEu9Lddk7eYduuvyZCENYclum486Lm9PKoZD");
//        param.setFbAccountId(CommonConstants.ViIRTUAL_FB_ID);
//        param.setBm(278941778970807L);
//        param.setCallBack(true);
//        param.setRemoveAccountFromUrl(true);
//        param.setResultClass(FBSingleId.class);
//        param.setFields("id");
//        param.setLimit(1000);
//        param.setApiPriorityCode(APIPriority.ProductCatalogCreate.getCode());
//        param.setApiCallbackTargetType(ApiCallBackTarget.Product.AddCatalog.getTargetType());
//        productCatalogFBService.getAllCatalogFromBM(param);
//        return 1L;
//
//        List<FBSingleId> ids = (List<FBSingleId>)message;
//
//        for(FBSingleId id: ids) {
//            CustomAudienceParam param = new CustomAudienceParam();
//            param.setAccessToken("CAAEJqYBYwW0BAH8hd4blFCEf5Wz2xMoImCG9ZAFil9ohifO7uKTyLt7fy4ybxM5Q4qQLaqsI0IQ5hBN8RUYGK2hWYTzfkQ0aKh9ywrK8AO5ueS2UKocq9ZAXGb5WK55QZANxbBUyqeHLJQMRFtk2S8rwX8iK6qEu9Lddk7eYduuvyZCENYclum486Lm9PKoZD");
//            param.setId(id.getId());
//            param.setFbAccountId(CommonConstants.ViIRTUAL_FB_ID);
//            customaudiencesFbServices.deleteCustomAudience(param);
//        }
    }

    /**
     * feed列表  某个的预览 取20个其中之一来展示
     * @param param
     */
    @RequestMapping("overview")
    public List<ProductCatalogStatusCheckResult> overview(@RequestBody FeedWe param)throws Exception{
        if(param != null && param.getId() != null){
            List<ProductCatalogStatusCheckResult> results = feedService.overview(param.getId());
            return results;
        } else {
            throw new CheckedException(ErrorType.PARAM_EXCEPTION);
        }
    }

    /**
     * feedName重名校验
     * @param param
     */
    @RequestMapping("validate")
    public Long validate(@RequestBody FeedWe param, HttpServletRequest req)throws Exception{
        User user = (User) req.getSession().getAttribute("user");
        if(param != null && StringUtil.isNotEmpty(param.getFeedName())){
            FeedWe feedWe = feedService.findByFeedName(user.getOrgId(), param.getFeedName());
            if(feedWe == null)
                return 1L;
            else if(feedWe.getId().equals(param.getId()))
                return 1L;
            else
                return 2L;
        } else {
            throw new CheckedException(ErrorType.PARAM_EXCEPTION);
        }
    }

    @RequestMapping("fetchNow")
    public Long update(@RequestBody FeedWe param, HttpServletRequest req)throws Exception{User user = (User) req.getSession().getAttribute("user");
        if(param != null && param.getId() != null){
            param.setUserId(user.getTicket());
            feedService.update(param.getId());
            return 1L;
        } else {
            throw new CheckedException(ErrorType.PARAM_EXCEPTION);
        }
    }

    /**
     * feed we从失败处重试
     * @param param
     * @param req
     * @return
     * @throws Exception
     */
    @RequestMapping("retry")
    public Long retry(@RequestBody FeedWe param, HttpServletRequest req)throws Exception{
        User user = (User) req.getSession().getAttribute("user");
        if(param != null && param.getId() != null){
            param.setUserId(user.getTicket());
            param.setNickName(StringUtil.isEmpty(user.getNickname()) ? user.getUsername() : user.getNickname());
            feedService.retry(param);
            return 1L;
        } else {
            throw new CheckedException(ErrorType.PARAM_EXCEPTION);
        }
    }

    @RequestMapping("getList")
    public Map<String, Object> getList(@RequestBody SearchListParam searchListParam, HttpServletRequest req)throws Exception{
        Map<String, Object> data = new HashMap<>();
        User user = (User) req.getSession().getAttribute("user");
        Integer sizeNo = searchListParam.getPSize() == null ? CommonConstants.DEFAULT_PAGE_SIZE_100 : searchListParam.getPSize();
        Integer firstResult = searchListParam.getCPage() == null ? 0 : (searchListParam.getCPage() - 1) * sizeNo;
        Pager<FeedWeWithMateriel> results = feedService.getFeedWithPager(user.getOrgId(), firstResult, sizeNo);
        if(results==null){
            results = new Pager<>();
            results.setPageIndex(sizeNo);
            results.setTotalSize(0L);
        }
        // 计算分页结果
        long tSize = results.getTotalSize();
        float nrOfPages = (float) tSize / sizeNo;
        int tPage = (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages);
        PageResult pageResult = new PageResult(tPage, searchListParam.getCPage(), searchListParam.getPSize(), tSize);
        // 封装响应结果
        data.put("feeds", results.getResultList());
        data.put("paginator", pageResult);
        return data;
    }

    /**
     * feed列表页 轮询状态
     * @param ids
     * @param req
     * @return
     * @throws Exception
     */
    @RequestMapping("searchByIds")
    public List<FeedWeWithMateriel> searchByIds(@RequestBody Long[] ids, HttpServletRequest req)throws Exception{
        List<FeedWeWithMateriel> results = feedService.searchByIds(ids);
        return results;
    }

    @RequestMapping("findByProd")
    public List<FeedWe> findByProd(@RequestParam(required = true) Long prodId) {
        return feedService.findFeedWeByProdId(prodId);
    }

    @RequestMapping("getFeed")
    public FeedWe getFeed(@RequestParam Long  feedId){
        return feedService.getFeed(feedId);
    }

    @RequestMapping("test1")
    public void test1(HttpServletRequest req) throws Exception{
        List<ChannelType> channelTypeList = new ArrayList<>();
        channelTypeList.add(ChannelType.EMAIL);
        channelTypeList.add(ChannelType.SMS);
        eventNotificationMessageProducerService.sendMonitorMessage("DEVOWNEREMAIL,PRODUCTOWNEREMAIL,DEVOWNERPHONE,PRODUCTOWNERPHONE", "test sms ", channelTypeList);

    }
}
